package com.school.graduation.goods.view;

import android.annotation.TargetApi;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.jude.rollviewpager.OnItemClickListener;
import com.jude.rollviewpager.RollPagerView;
import com.school.graduation.R;
import com.school.graduation.common.base.BaseFragment;
import com.school.graduation.goods.presenter.GoodsFragmentPresenter;
import com.school.graduation.goods.presenter.HotMarketAdapter;
import com.school.graduation.goods.presenter.RecommendRecyclerAdapterNew;
import com.school.graduation.goods.presenter.RollPagerAdapter;
import com.school.graduation.util.NetWorkUtil;
import com.school.graduation.util.ToastUtil;

import butterknife.Bind;
import butterknife.OnClick;

public class GoodsFragment extends BaseFragment
        implements ImplGoodsFragment {

    @Bind(R.id.recycler)
    RecyclerView recommendRecycler;
    @Bind(R.id.roll_pager)
    RollPagerView rollPager;
    @Bind(R.id.scroll)
    ScrollView scroll;
    @Bind(R.id.find_rectangle)
    LinearLayout findRectangle;
    @Bind(R.id.find_good_bar)
    LinearLayout findGoodBar;
    @Bind(R.id.parent_layout)
    RelativeLayout parentLayout;
    @Bind(R.id.hot_market_recycler)
    RecyclerView hotMarketRecycler;
    @Bind(R.id.recommend_below_top)
    LinearLayout recommendBelowTop;
    @Bind(R.id.recommend_static)
    TextView recommentStatic;
    @Bind(R.id.hint_text)
    TextView textHintLoadError;

    private float mY_recommend, recommendY;
    private Boolean firstY = true;
    private int[] recommend = new int[2];
    private GoodsFragmentPresenter presenter;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private MaterialDialog progressDialog;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int getFragmentView() {
        return R.layout.fragment_goods;
    }

    @Override
    public void initData() {
        initSp();
        presenter = new GoodsFragmentPresenter(context, this);
        getRecommendY();                  //获取推荐的y坐标
        setScrollChangeListener();        //设置scroll的变化监听事件及其处理
        initPictureCarousel();            //图片轮播
        initHotMarket();                  //热门市场
        initRecommend();                  //推荐
    }

    private void getRecommendY() {
        float mY = sp.getFloat("recommendY",0);
        if (mY!=0) recommendY = mY;
        else setViewTreeGlobalListener();      //设置视图树监听scrollview是否绘制完成
    }

    private void initSp() {
        sp = context.getSharedPreferences("good",0);
        editor = sp.edit();
    }

    /*
    推荐的初始化
     */
    private void initRecommend() {
        initRecommendRecycler();
        initRecommendDate();
    }

    private void initRecommendDate() {
        if (NetWorkUtil.isNetWorkConnected(context)){
            textHintLoadError.setVisibility(View.GONE);
            //presenter.getRecommendMsgFromBmob();
            presenter.getAllMsgFromNet();
        }else {
            ToastUtil.makeShortToast(context,"请检查网络连接");
            textHintLoadError.setVisibility(View.VISIBLE);
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void initRecommendRecycler() {
        LinearLayoutManager manager = new LinearLayoutManager(context) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        recommendRecycler.setLayoutManager(manager);
    }
    /*
    热门市场的初始化
     */
    private void initHotMarket() {
        hotMarketRecycler.setLayoutManager(new GridLayoutManager(context, 3) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        presenter.getHotMarket();
    }

    /*
    图片轮播的初始化
     */
    private void initPictureCarousel() {
        presenter.getPicRotationFromBmob();
    }

    /*
    设置view树监听器 获取“推荐”栏的y坐标
     */
    private void setViewTreeGlobalListener() {
        scroll.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                getRecommentYLocation();          //获取到静态推荐的y坐标
            }
        });
    }

    /**
     * 对top背景颜色的变化
     */
    @TargetApi(Build.VERSION_CODES.M)
    private void setScrollChangeListener() {
        scroll.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY > 600) {
                    findGoodBar.setAlpha(1);
                    findRectangle.setAlpha(1);
                } else {
                    findGoodBar.setAlpha(scrollY / 600f);
                }
                if (scrollY > recommendY) recommendBelowTop.setVisibility(View.VISIBLE);
                else recommendBelowTop.setVisibility(View.GONE);
            }
        });
    }

    /*
    拿到静止的推荐栏的y坐标
     */
    private void getRecommentYLocation() {
        recommentStatic.getLocationOnScreen(recommend);
        mY_recommend = recommend[1] - findGoodBar.getMeasuredHeight();
        if (firstY) {
            recommendY = mY_recommend;
            editor.putFloat("recommendY",mY_recommend);
            editor.commit();
            firstY = false;
        }
    }

    @Override
    public void setPicRotationAdapter(RollPagerAdapter adapter) {
        rollPager.setAdapter(adapter);
    }

    @Override
    public void setHotMarketAdapter(HotMarketAdapter adapter) {
        hotMarketRecycler.setAdapter(adapter);
    }

    @Override
    public void showProgressDialog() {
        progressDialog = new MaterialDialog.Builder(context)
                .progress(true,0)
                .content("正在加载...")
                .canceledOnTouchOutside(false)
                .build();
        progressDialog.show();
    }

    @Override
    public void dismissProgressDialog(){
        progressDialog.dismiss();
    }

    @Override
    public void setRecommendAdapterNew(RecommendRecyclerAdapterNew adapter) {
        recommendRecycler.setAdapter(adapter);
    }

    @OnClick(R.id.find_rectangle)
    public void onClick() {
        Bundle bundle = new Bundle();
        FoundGoodsActivity.jumpToFoundActivity(context,bundle);
    }

    @OnClick(R.id.hint_text)
    public void clickHintText(){
        scroll.scrollTo(0,0);
        initPictureCarousel();
        initRecommend();
    }
}
